import json
import csv
import os
import json
from utils import log_info

def json_to_csv(json_path, csv_path):
    """将JSON文件转换为CSV文件，丢弃id字段"""
    log_info(f"开始将 {json_path} 转换为 {csv_path}")
    try:
        # 读取JSON文件
        with open(json_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        if not data or not isinstance(data, list):
            raise ValueError("JSON文件格式不正确，应为数组形式")

        # 确定CSV文件的字段名（排除id）
        if not data[0]:
            raise ValueError("JSON数据为空")

        fieldnames = [key for key in data[0].keys() if key != 'id']

        # 写入CSV文件
        with open(csv_path, 'w', newline='', encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            # 不写入标题行

            for item in data:
                # 移除id字段
                if 'id' in item:
                    del item['id']
                writer.writerow(item)

        logger.log_info(f"成功将 {json_path} 转换为 {csv_path}")
        logger.log_info(f"共转换 {len(data)} 条记录")
        return True
    except Exception as e:
        logger.log_error(f"转换过程中出错: {str(e)}")
        return False

if __name__ == "__main__":
    # 定义文件路径
    json_file_path = os.path.join(os.path.dirname(__file__), 'data', 'tk.json')
    csv_file_path = os.path.join(os.path.dirname(__file__), 'data', 'tk_csv.csv')

    # 执行转换
    json_to_csv(json_file_path, csv_file_path)